<?php
/* 
 * Copyright (c) 2018-2021   All rights reserved.
 * 
 * 创建时间：2021-11-04 14:28
 *
 * 项目：rm  -  $  - LevfmDatasChild.php
 *
 * 作者：liwei 
 */

namespace modules\levfm\table;

use Lev;
use lev\base\Modelv;
use lev\base\SubModelv;

!defined('INLEV') && exit('Access Denied LEV');


class LevfmDatasChild extends SubModelv
{

    public static $tableName = '{{%levfm_datas_child}}';

    public static function saveChild($upData) {
        $upData = static::safeColumnsGen($upData);
        $upData['uptime'] = Lev::$app['timestamp'];
        $ck = static::findOne(['id'=>$upData['id']], 'id')
            ? static::update($upData, ['id'=>$upData['id']])
            : static::insert($upData, true);
        return $ck;
    }

    public static function safeColumnsGen($columns)
    {
        //return parent::safeColumnsGen($columns); // TODO: Change the autogenerated stub
        $allColumns = static::allColumns();
        if (is_array($allColumns)) {
            foreach ($columns as $field => $value) {
                if (!isset($allColumns[$field])) unset($columns[$field]);
            }
        }
        return $columns;
    }

    public static function allColumns() {
        return array(
            'id'       => 'Id',

            'uid'      => '用户UID',

            'formid'   => '关联表单ID',

            'srhkey'   => '搜索关键字',

            'srhtype'  => '分类搜索项',

            'uptime'   => '更新时间',

        );
    }

    /**
     * 关键词加或去前缀 # 号
     * @param $srhkey
     * @param string $pre
     * @return bool|string
     */
    public static function setSrhkey($srhkey, $pre = '#') {
        return $pre ? ($srhkey[0] == $pre ? '' : $pre).Lev::cutString($srhkey, 200, '') : ($srhkey[0] == '#' ? substr($srhkey, 1) : $srhkey);
    }

    /**
     * 设置分类搜索项，唯一字段项
     * @param $fieldid
     * @param $value
     * @param bool $encode
     * @return false|string
     */
    public static function setSrhString($fieldid, $value, $encode = true) {
        $string = $fieldid . '=' . $value;
        return $encode ? json_encode($string) : $string;
    }

    /**
     * 格式化分类搜索，唯一字段
     * @param $srhTypes
     * @return false|string
     */
    public static function setSrhtype($srhTypes)
    {
        if ($srhTypes) {
            foreach ($srhTypes as $_fieldid => $value) {
                if (is_array($value)) {
                    foreach ($value as $v) {
                        $result[] = static::setSrhString($_fieldid, $v, false);
                    }
                } else {
                    $result[] = static::setSrhString($_fieldid, $value, false);
                }
            }
        }

        return empty($result) ? '' : json_encode($result);
    }

}